//
//  DBUserAccountViewModel.swift
//  大波微博swift
//
//  Created by 大波 on 16/2/28.
//  Copyright © 2016年 zhaojin. All rights reserved.
//

import UIKit

class DBUserAccountViewModel: NSObject {

    //单例
    static let shareUserAccountViewModel: DBUserAccountViewModel = DBUserAccountViewModel()
    
    //账户模型
    var userAccount: DBUserAccount?
    
    //用户是否登陆
    var isUserLogin: Bool {
        
        get {
            
            return (userAccount != nil) ? true : false
        }
    }
    
    //保存用户数据的沙盒路径
    let accountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingString("/Account.plist")
    
    //重写构造方法 当第一次访问这个单例就自动解档
    private override init() {
        
        super.init()
        
        userAccount = loadUserAccount()
    }
    
    /**
         加载token
     
     - parameter codeString:                      截取的code
     - parameter loadAccessTokenCallBlockClosure: 传错误的闭包
     */
    func loadAccessToken(codeString: String, loadAccessTokenCallBlockClosure: (error: NSError?) -> ()) {
        
        //处理数据
        DBNetworkTool.shareNetworkTool.loadToken(codeString) {
            
            (response: [String : AnyObject]?, error: NSError?) -> () in
            
            //模拟授权失败
//            error = NSError(domain: "1", code: 1, userInfo: nil)
            
            if error != nil {
                
                //用闭包传错误过去
                loadAccessTokenCallBlockClosure(error: error)
                
                return
            }
            
            //用户模型
            self.userAccount = DBUserAccount(dic: response!)
            
            //保存用户数据到沙盒
            self.saveUserAccount()
            
            loadAccessTokenCallBlockClosure(error: nil)
        }
    }
    
    ///保存用户数据到沙盒
    private func saveUserAccount() {
        
        if userAccount != nil {
            
            NSKeyedArchiver.archiveRootObject(userAccount!, toFile: accountPath)
        }
    }
    
    ///从沙盒读取数据
    private func loadUserAccount() -> DBUserAccount? {
        
        let account = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? DBUserAccount
        
        if account != nil && account?.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            
            print("account: \(account)")
            
            return account
        }
        
        return nil
    }
    
    ///加载userInfo
    func loadUserInfo(loadUserCallBack: (error: NSError?) -> ()) {
        
        DBNetworkTool.shareNetworkTool.loadUserInfo { (userInfo, error) -> () in
            
            if error != nil {
                
                loadUserCallBack(error: error)
                
                return
            }
            
            self.userAccount?.screen_name = userInfo!["screen_name"] as? String
            
            self.userAccount?.avatar_large = userInfo!["avatar_large"] as? String
            
            self.saveUserAccount()
            
            loadUserCallBack(error: nil)
        }
    }
}

















